package com.example.controller;

import com.example.entity.Result;
import com.example.entity.SeckillResult;
import com.example.service.other.SeckillCoreService;
import com.example.service.other.SseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import static com.example.entity.constant.redis.SeckillConstant.RESULT_KEY_PREFIX;

@RestController
@RequestMapping("/api/seckill")
public class SeckillController {

    @Autowired
    private SeckillCoreService seckillCoreService;

    @Autowired
    private SseService sseService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发起秒杀请求
     * @param userId 用户ID
     * @param goodsId 商品ID
     * @return 包含令牌的响应
     */
    @PostMapping
    public Result<String> startSeckill(@RequestParam Long userId, @RequestParam Long goodsId) {
        return seckillCoreService.doSeckill(userId, goodsId);
    }

    /**
     * 建立SSE连接，用于接收秒杀结果推送
     * @param token 秒杀令牌
     * @return SseEmitter对象
     */
    @GetMapping("/sse-connect")
    public SseEmitter connectSse(@RequestParam String token) {
        return sseService.createSseConnection(token);
    }

    /**
     * 用于降级方案，查询秒杀结果
     * 也就是建立SSE连接用户获取结果失败
     * @param token 秒杀令牌
     * @return 秒杀结果
     */
    @GetMapping("/result")
    public Result<SeckillResult> getResult(@RequestParam String token) {
        String resultKey = RESULT_KEY_PREFIX + token;
        String status = redisTemplate.opsForValue().get(resultKey);

        SeckillResult result = new SeckillResult();
        result.setToken(token);

        if (status == null) {
            result.setStatus("INVALID");
            result.setMessage("抢购已过期");
        } else if ("PROCESSING".equals(status)) {
            result.setStatus("PROCESSING");
            result.setMessage("正在抢购中，请稍候...");
        } else if ("SUCCESS".equals(status)) {
            result.setStatus("SUCCESS");
            result.setMessage("恭喜，秒杀成功！");
            // 实际应用中这里可以查询订单服务获取订单ID
        } else {
            result.setStatus("FAIL");
            result.setMessage("抱歉，商品已抢完~");
        }

        return Result.success(result);
    }
}
